# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# 惠付拉支付
APP_CONF = {
    'witch': {  # 支付宝 10-5000 witch
        'API_KEY': '67d8a3000ba44add0fccef055a34b925',
        'gateway': 'http://ccb.lanmeibank.com/api/v1/order/add',
        'query_gateway': 'http://ccb.lanmeibank.com/api/v1/order/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s = s[:-1] + str(key)
    _LOGGER.info('huifulapay sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("futurepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    """ 支付方式 1支付宝 2微信 """
    if service == 'alipay':
        return '1'
    return '1'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('cope_pay_amount', str(int(pay_amount * 100))),
        ('merchant_open_id', '61839ccb9ac0506ecd06ffbd06161ece'),
        ('merchant_order_number', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/huifulapay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('pay_type', _get_pay_type(service)),
        ('pay_wap_mark', 'pay004'),
        ('subject', 'charge'),
        ('timestamp', int(time.time() * 1000)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    url = _get_gateway(app_id)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    _LOGGER.info("huifulapay create: url: %s, %s", url, json.dumps(parameter_dict))
    response = requests.post(url, data=json.dumps(parameter_dict), headers=headers, timeout=5)
    _LOGGER.info("huifulapay create: response: %s", response.text)
    order_db.fill_third_id(str(pay.id), json.loads(response.text)['out_trade_no'])
    return {'charge_info': json.loads(response.text)['pay_url']}


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("huifulapay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['merchant_order_number']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huifulapay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = data['state']
    trade_no = data['out_trade_no']
    total_fee = float(data['cope_pay_amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0' and total_fee > 0.0:
        _LOGGER.info('huifulapay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('timestamp', int(time.time() * 1000)),
        ('out_trade_no', pay_order.third_id),
        ('merchant_open_id', '61839ccb9ac0506ecd06ffbd06161ece'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('huifulapay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info('huifulapay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['mark']
        total_fee = float(data['cope_pay_amount']) / 100.0
        trade_no = str(data['out_trade_no'])
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '0' and total_fee > 0.0:
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('huifulapay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
